mod utils;
mod example;
mod command;
mod entity;
mod config;
mod service;
mod api;
mod front;

use tauri::Manager;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use log::{info,error};
use crate::utils::js_bridge::init_js_bridge;
use crate::utils::{TaskManager};
use crate::command::{stop_background_tasks, js_callback, greet,js_initialized,shelf_list,shelf_monitor,shelf_statistics};
use crate::utils::db_init::DBInit;
use crate::utils::db_util::{DBUtil, init_global_db_pool};
use utils::db_migrations::run_migrations;
use crate::utils::setup_logger::setup_logger;
use crate::utils::http_auth_manage::{js_set_auth_info};

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    // 初始化 Tokio 运行时并包装在 Arc 中
    let rt = Arc::new(tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .worker_threads(24) // 指定8个线程
        .build()
        .unwrap());
    // let rt = Arc::new(tokio::runtime::Runtime::new().unwrap());

    // 初始化全局 TaskManager 实例
    TaskManager::init_global(&rt);

    // 启动 Tauri 应用主循环
    tauri::Builder::default()
        .setup(move |app| {
            let app_handle = app.app_handle(); // 获取正确的 AppHandle
            let app_name = app.package_info().name.clone();

            setup_window_close_handler(&app_handle);
            setup_logger(&app_handle)?;

            // 初始化 JS 调用管理器实例
            init_js_bridge(app_handle.clone());
            // 注册数据库工具实例
            init_global_db_pool(init_db_pool(app_name).expect("无法初始化数据库连接池"));
            //全局注入appHandle
            //set_global_app_handle(app_handle.clone());
            // example::test();
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![stop_background_tasks,js_callback,greet,js_set_auth_info,js_initialized,shelf_list,shelf_monitor,shelf_statistics])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

// 设置窗口关闭事件监听
fn setup_window_close_handler(app: &tauri::AppHandle) {
    if let Some(window) = app.get_webview_window("main") {
        let window_for_event = window.clone();
        window_for_event.on_window_event(move |event| {
            if let tauri::WindowEvent::CloseRequested { .. } = event {
                log::info!("【主程序】检测到窗口关闭事件，准备停止后台任务...");
                let running_for_ipc = TaskManager::global().running.clone();
                running_for_ipc.store(false, Ordering::SeqCst);
            }
        });
    }
}
// 初始化数据库连接池
fn init_db_pool(app_name: String) -> Result<Arc<DBUtil>, Box<dyn std::error::Error + Send + Sync>> {
    // 使用DBInit初始化数据库连接池
    let rt = tokio::runtime::Runtime::new().unwrap();
    let db_util = rt.block_on(DBInit::init_pool(app_name))?;

    // 运行数据库迁移
    if let Err(e) = rt.block_on(run_migrations(&db_util)) {
        error!("数据库迁移失败: {}", e);
    }

    info!("数据库连接池已成功初始化");
    Ok(db_util)
}